class HomeController < ApplicationController
  before_filter :find_user, :only => [:edit, :view]
  before_filter :authorize, :only => [:logout] # overrides :authorize from application_controller
  before_filter :restricted_access, :only => [:view, :edit]
  
  def index
  end
  
  def show
    case params[:id]
      when "login": logged_in? ? redirect_to(:action => "index") : login
      when "logout": logged_in? ? logout : redirect_to(:action => "index")
      else redirect_to(:action => "index")
    end
  end
  
  def login
    if request.post? 
      user = User.authenticate(params[:name], params[:password]) 
      if user
        session[:user_id] = user.id
        uri = session[:original_uri] 
        session[:original_uri] = nil
        if uri
          redirect_to uri 
        else 
          redirect_to :action => "index"
        end
      else 
        flash.now[:notice] = "Invalid user/password combination" 
      end 
    end      
  end
  
  def logout 
    session[:user_id] = nil 
    flash[:notice] = "Logged out" 
    redirect_to :action => "index"
  end  
  
  
  
  protected 
  
  def authorize
    user = User.find_by_id(session[:user_id])
    unless user # NOT LOGGED IN
      session[:original_uri] = request.request_uri
      flash[:notice] = "Please log in" 
      redirect_to :action => "login"
    end 
  end
  
  def restricted_access
    user = User.find_by_id(session[:user_id])
    if @user
      if user.access < 1
        unless user.id == @user.id # if trying to access other profiles
          flash[:notice] = "You do not have suffiecient priviledges to view this area" 
          redirect_to :controller => "home"
        end
      end
    end
  end
  
  
  
  private
  
  def find_user
    begin
      @user = User.find(params[:id])
    rescue
      redirect_to request.request_uri
    end
  end
  
end
